<template>
    <ContentBase v-if="!$store.state.user.pulling_info">
        <div class="row justify-content-md-center">
            <div class="col-3">
                <form @submit.prevent="login">
                    <div class="mb-3">
                        <label for="username" class="form-label">用户名</label>
                        <input v-model="username" type="text" class="form-control" id="username">
                    </div>
                    <div class="mb-3">
                        <label for="password" class="form-label">密码</label>
                        <input v-model="password" type="password" class="form-control" id="password">
                    </div>
                    <div class="error-message">{{ error_message }}</div>
                    <button type="submit" class="btn btn-primary">登录</button>
                </form>
            </div>
        </div>
    </ContentBase>
</template>

<script setup>
import ContentBase from '../components/ContentBase';
import { ref } from 'vue';
import { useStore } from 'vuex';
import router from '@/router/index';
import $ from 'jquery';

const store = useStore();
let username = ref('');
let password = ref('');
let error_message = ref('');

const jwt_token = localStorage.getItem("jwt_token");
if (jwt_token) {
    $.ajax({
        url: "http://localhost:3000/api/account/info",
        type: "GET",
        headers: {      // jwt验证写法
            'Authorization': "Bearer " + jwt_token,
        },
        success(resp) {     
            store.commit("updateUser", {
                ...resp,    // 将resp解构
                token: jwt_token,
                is_login: true,
            });
            if (store.state.user.identity == 'dormAdmin') {
                router.push({name: 'pending'});
            } else if (store.state.user.identity == 'sysAdmin') {
                router.push({name: 'BuildingManage'});
            } else {
                router.push({name: 'UnreadEvent'});
            }
            store.commit("updatePullingInfo", false);
        },
        error() {
            store.commit("updatePullingInfo", false);
        }
    })
} else {
    store.commit("updatePullingInfo", false);
}

const login = () => {
    error_message.value = "";   // 登录的时候将错误信息清空
    // dispatch用来调用user的actions里的变量（函数），将变量名作为第一个参数，第二个参数可以任意传
    store.dispatch("login", {
        username: username.value,
        password: password.value,
        success() {
            if (store.state.user.identity == 'dormAdmin') {
                router.push({name: 'pending'});
            } else if (store.state.user.identity == 'sysAdmin') {
                router.push({name: 'BuildingManage'});
            } else {
                router.push({name: 'UnreadEvent'});
            }
        },
        error() {
            error_message.value = "用户名或密码错误";
        }
    });
};

</script>

<style scoped>

button {
    width: 100%;
}

.error-message {
    color: red;
}

</style>